<?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as LumenController;
use Illuminate\Http\Request;
use App\Libs\Commons\MyException;
use App\Libs\Commons\MyMessage;
use App\Libs\Commons\MyLogger;
use Illuminate\Support\Facades\DB;

class InitController extends LumenController
{
    public function __construct()
    {
        $this->enableQueryLog();
    }

    /**
     * @param Request $req
     * @param string $apiv 版本号
     * @param string $module 模块
     * @param string $ctl 控制器
     * @param string $action 动作
     * @throws \Exception
     * @author zhe.wang
     * @desc Api入口
     */
    public function Api(Request $req, $apiv, $module, $ctl, $action)
    {
        try {
            if (empty($apiv) || empty($module) || empty($ctl)) {
                throw new MyException(MyMessage::PARAM_LOSE);
            }
            $versionIndex = intval(substr($apiv, 1));

            if ($versionIndex < 1) {
                throw new MyException(MyMessage::ERROR);
            }

            $max = 100;  #定义最大查找版本次数

            $project = $req->segment(1);

            while ($max > 0 && $versionIndex > 0) {
                //组装版本V
                $apiv = 'v' . $versionIndex;
                //组装controller的名字
                $ctlName = __NAMESPACE__ . '\\'
                    . ucfirst($project) . '\\' . ucfirst($apiv) . '\\' . ucfirst($module) . '\\' . ucfirst($ctl) . 'Controller';
                if (class_exists($ctlName)) {
                    $ctl_obj = app($ctlName);
                    if (method_exists($ctl_obj, $action)) {
                        return $ctl_obj->$action($req);
                    } else {
                        throw new MyException(MyMessage::SYSTEM_CTL_ACTION_NOT_FOUND);
                    }
                    break;
                } else {
                    throw new MyException(MyMessage::SYSTEM_CTL_NOT_FOUND);
                }

                $versionIndex--;
                $max--;
            }
        } catch (MyException $e) {
            MyLogger::log(MyLogger::ERROR, 'Init::api:MyException', [$e->getCode(), $e->getFile(), $e->getLine(), $e->getMessage()]);
            return My_error($e->getCode(), $e->getMessage());
        } catch (\Throwable $e) {
            MyLogger::log(MyLogger::ERROR, 'Init::api:Throwable', [$e->getCode(), $e->getFile(), $e->getLine(), $e->getMessage()]);
            if (MyDebuger()) {
                return My_error(MyMessage::UNKNOWN_ERROR, $e->getFile() . ':' . $e->getLine() . ' ' . $e->getMessage());
            }
            return My_error(MyMessage::UNKNOWN_ERROR);
        }
    }

    /**
     * @param Request $req
     * @param string $module 模块名
     * @param string $class 类名&文件名
     * @param string $action 动作名
     * @return \Illuminate\Http\JsonResponse
     * @author  zhe.wang
     * @desc    后台入口
     */
    public function Admin(Request $req, $module, $ctl, $action)
    {
        $project = $req->segment(1);

        try {
            $ctlName = __NAMESPACE__ . '\\' . ucfirst($project) . '\\' . ucfirst($module) . '\\' . ucfirst($ctl) . 'Controller';
            if (class_exists($ctlName)) {
                $ctl_obj = app($ctlName);
                if (method_exists($ctl_obj, $action)) {
                    return $ctl_obj->$action($req);
                } else {
                    throw new MyException(MyMessage::SYSTEM_CTL_ACTION_NOT_FOUND);
                }
            } else {
                throw new MyException(MyMessage::SYSTEM_CTL_NOT_FOUND);
            }
        } catch (MyException $e) {
            MyLogger::log(MyLogger::ERROR, 'Init::admin:MyException', [$e->getCode(), $e->getFile(), $e->getLine(), $e->getMessage()]);
            return My_error($e->getCode(), $e->getMessage());
        } catch (\Throwable $e) {
            MyLogger::log(MyLogger::ERROR, 'Init::admin:Throwable', [$e->getCode(), $e->getFile(), $e->getLine(), $e->getMessage()]);
            if (MyDebuger()) {
                return My_error(MyMessage::UNKNOWN_ERROR, $e->getFile() . ':' . $e->getLine() . ' ' . $e->getMessage());
            }
            return My_error(MyMessage::UNKNOWN_ERROR);
        }
    }

    /**
     * @author    zhe.wang
     * @desc        rpc入口
     */
    public function Rpc()
    {
        MyLogger::log(MyLogger::INFO, 'RpcClientConnection');
    }

    private function enableQueryLog()
    {
        DB::enableQueryLog();
    }

    private function saveQueryLogRecord()
    {
        $sqlLogs = DB::getQueryLog();
        if (!empty($sqlLogs)) {
            $sqlDebug = request('sqlDebug');
            foreach ($sqlLogs as $k => $v) {
                #无sqlDebug，不记录select语句sql
                if (!$sqlDebug && strpos(ltrim($v['query']), 'select') === 0) {
                    continue;
                }
                MyLogger::log(MyLogger::DEBUG, 'sqlLog', $v);
            }
        }
    }

    public function __destruct()
    {
        $this->saveQueryLogRecord();
    }
}
